package com.ayf.payment.game.api.controller.ayb;

import com.ayf.payment.game.api.bean.BaseResData;
import com.ayf.payment.game.api.dto.MerchantDTO;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.service.payment.ayb.MerchantTwoService;
import com.ayf.payment.game.api.type.CommonConstants;
import com.ayf.payment.game.api.utils.CommonResult;
import com.ayf.payment.game.api.utils.FtpUtil;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@RestController
@RequestMapping("/t1")
public class MerchantFtpController {

    @Autowired
    private MerchantTwoService merchantTwoService;
    /**
     * 上传FTP文件
     * @param file
     * @param merchantDTO
     * @return
     */
    @PostMapping("/f/upload_file")
    public CommonResult<BaseResData> upload(@RequestParam("file") MultipartFile file, MerchantDTO merchantDTO) {
        String traceId = SnowFlakeUtils.getUniqueId();
        CommonResult commonResult=new CommonResult();
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!"jpg".equals(suffix) && !"png".equals(suffix) && !"jpeg".equals(suffix)) {
            LogPortal.error("{} 商户[{}]图片上传失败，文件格式错误，仅支持jpg、png、jpeg，当前文件格式：{}", traceId, merchantDTO.getId(), suffix);
            throw new ParameterException("上传失败，图片格式错误，仅支持jpg、png、jpeg格式");
        }
        /**if (file.getSize() > 1024 * 1100) {
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "图片过大，仅支持1M之下的图片");
        }**/
        String fileName=SnowFlakeUtils.getUniqueId();
        try {
            fileName=fileName+"."+suffix;
            BaseResData baseResData= FtpUtil.uploadXYFile(file.getBytes(),fileName,"",traceId);
            if(baseResData.isSuccess()){
                return new CommonResult(CommonConstants.RETURN_SUCCESS, "上传成功", baseResData);
            }else{
                return new CommonResult(CommonConstants.RETURN_ERROR, "上传失败", "上传失败，错误码：" + traceId);
            }

        } catch (Exception e) {
            LogPortal.error("[{}]图片上传发生[{}]异常,异常信息为[{}]", traceId, e.getClass().getSimpleName(), e.getMessage());
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "上传失败，错误码：" + traceId);
        }
    }

    /**
     * 下载FTP文件
     */
    @GetMapping("/f/down_file")
    public void downLoadFile(@RequestParam("fileName") String fileName, HttpServletResponse response){
        String traceId = SnowFlakeUtils.getTraceId();
        if(StringUtils.isBlank(fileName)){
            throw new ParameterException("下载文件名不能为空");
        }
        ServletOutputStream outputStream = null;
        try {
                byte[] bytes = FtpUtil.downloadXYFile("",fileName);
                String suffix = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf(".") + 1);
                response.setContentType("image/" + suffix);
                outputStream = response.getOutputStream();
                outputStream.write(bytes);

        } catch (Exception e) {
            LogPortal.error("[{}]图片下载发生[{}]异常，异常信息为: {}", e, traceId, e.getClass().getSimpleName(), e.getMessage());
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                LogPortal.error("图片下载关闭流时发生IOException，异常信息为: {}", e, e.getMessage());
            }
        }
    }
}
